package com.huawei.statistics.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by op on 2017/11/3.
 */
@Configuration
@PropertySource(ignoreResourceNotFound = true, value = {"classpath:config.properties"})
public class RedisConfig {

    @Bean
    public JedisPoolConfig getJedisPoolConfig(@Value("${redis.maxIdle}") int maxIdle,
                                              @Value("${redis.maxActive}") int maxActive,
                                              @Value("${redis.maxWait}") int maxWait,
                                              @Value("${redis.testOnBorrow}") boolean testOnBorrow,
                                              @Value("${redis.testOnReturn}") boolean testOnReturn,
                                              @Value("${redis.connectionTimeout}") int connectTimeOut,
                                              @Value("${redis.soTimeout}") int soTimeOut) {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxTotal(maxActive);
        jedisPoolConfig.setMaxWaitMillis(maxWait);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestOnReturn(testOnReturn);
        return jedisPoolConfig;
    }
    @Bean
    public ShardedJedisPool getShardedJedisPool(JedisPoolConfig jedisPoolConfig,List<JedisShardInfo> shardInfos){
        ShardedJedisPool shardedJedisPool=new ShardedJedisPool(jedisPoolConfig,shardInfos);
        return shardedJedisPool;
    }

    @Bean
    public List<JedisShardInfo> getJedisShardInfo(@Value("${redis.uri}")URI uri,
                                                  @Value("${redis.connectionTimeout}")int connectTimeout,
                                                  @Value("${redis.soTimeout}")int soTimeout){
        JedisShardInfo jedisShardInfo=new JedisShardInfo(uri);
        jedisShardInfo.setConnectionTimeout(connectTimeout);
        jedisShardInfo.setSoTimeout(soTimeout);
        List<JedisShardInfo> jedisShardInfoList=new ArrayList<>();
        jedisShardInfoList.add(jedisShardInfo);
        return jedisShardInfoList;
    }
}
